use axum_app_common::{
    error::BizError,
    model::{BizRequest, BizResponse, PageRequest},
    service_store, BizHandler, BizHandlerResult, ServiceStore,
};
use axum_app_dao::rbac_user_role_rel_dal::{self, RbacUserRoleRelQueryCondition};

use crate::model::rbac::UserRolesQueryPageParams;

pub struct RbacHandler;

impl BizHandler for RbacHandler {
    fn service_map() -> ServiceStore {
        service_store! {
            ("rbac.user.roles.query.page","查询用户的角色列表") => user_roles_query_page
        }
    }
}

pub async fn user_roles_query_page(request: BizRequest) -> BizHandlerResult {
    let _ = request.get_context();
    let state = request.get_state().unwrap();
    let db = &state.db_conn;

    let biz_content = request.get_biz_content();

    let params = PageRequest::<UserRolesQueryPageParams>::try_from(biz_content)?;

    let Some(query_params) = params.params else {
        return Err(BizError::InvalidParams(None).into());
    };

    let userid = query_params.userid;
    println!("userid={}", userid);

    let page_res = rbac_user_role_rel_dal::RbacUserRoleRelQuery::query_page(
        db,
        params.page_num,
        params.page_size,
        RbacUserRoleRelQueryCondition::new(vec![]).user_id_eq(Some(&userid)),
    )
    .await;

    Ok(BizResponse::success(page_res.into()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum_app_dao::rbac_user_role_rel_dal::{self, RbacUserRoleRelQueryCondition};
    use serde_json::json;
    #[tokio::test]
    async fn test() {
        let biz_content = json!({"page_num":1,"page_size":10,"params":{"userid":"1c018f4c0c184041ac089540891a37476523"}});
        let params = PageRequest::<UserRolesQueryPageParams>::try_from(&biz_content);
        println!("{:?}", params);

        let params = params.unwrap();

        let userid = params.params.unwrap().userid;

        let db = axum_app_common::test::get_connect().await;

        let page_res = rbac_user_role_rel_dal::RbacUserRoleRelQuery::query_page(
            &db,
            params.page_num,
            params.page_size,
            RbacUserRoleRelQueryCondition::new(vec![]).user_id_eq(Some(&userid)),
        )
        .await;

        println!("page query res : {:?}", page_res);
    }
}
